package com.sunflower.common.mybatis.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.sunflower.common.core.interceptor.SFunction;
import com.sunflower.common.core.utils.reflect.ReflectUtils;

import java.lang.reflect.Field;

/**
 * @author: SunLuQuan
 * @Date: 2024年08月02日 21:01
 * @Description: TableUtils
 * TODO
 */
public class TableUtils {

    /**
     *
     * @param columnFun
     * @return
     * @param <T>
     */
    public static <T> String getColumnName(SFunction<T, ?> columnFun) {
        Field field = ReflectUtils.findField(columnFun);
        String name = field.getName();
        Class<T> t = (Class<T>) field.getDeclaringClass();
        TableInfo tableInfo = TableInfoHelper.getTableInfo(t);
        for (TableFieldInfo tableFieldInfo : tableInfo.getFieldList()) {
            if (StrUtil.equals(tableFieldInfo.getProperty(), name)) {
                return tableFieldInfo.getColumn();
            }
        }
        return name;
    }
}
